﻿using CleanArchitecture.Core;
using CleanArchitecture.Core.Configuration;
using CleanArchitecture.Core.Helper;
using CleanArchitecture.Infrastructure.Entities;
using CleanArchitecture.Infrastructure.Entities.AdminUsers;
using CleanArchitecture.Infrastructure.Entities.Business;
using CleanArchitecture.Infrastructure.Entities.Common;
using CleanArchitecture.Infrastructure.Entities.Settings;
using CleanArchitecture.Infrastructure.Interfaces;
using CleanArchitecture.Infrastructure.Interfaces.Business;
using CleanArchitecture.Infrastructure.Interfaces.Common;
using CleanArchitecture.Infrastructure.Interfaces.Media;
using CleanArchitecture.Infrastructure.Interfaces.Security;
using CleanArchitecture.Infrastructure.Interfaces.SystemManage;
using CleanArchitecture.Infrastructure.Models.Business.Advertises;
using CleanArchitecture.Infrastructure.Models.Business.Blog;
using CleanArchitecture.Infrastructure.Models.Business.Columns;
using CleanArchitecture.Infrastructure.Models.Business.Comments;
using CleanArchitecture.Infrastructure.Models.Business.FileUpload;
using CleanArchitecture.Infrastructure.Models.Business.News;
using CleanArchitecture.Web.Factories;
using CleanArchitecture.Web.Filters;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CleanArchitecture.Web.Controllers.Backend.Business
{
    public class BackendBusinessController : BaseAdminController
    {
        #region Field
        private readonly IWorkContext _workContext;
        private readonly NewsSettings _newsSettings;
        private readonly BlogSettings _blogSettings;
        private readonly ILanguageService _languageService;
        private readonly IGenericAttributeService _gaService;
        private readonly IPermissionService _permissionService;
        private readonly IFileUploadService _fileuploadService;
        private readonly ISystemModuleService _systemmoduleService;
        private readonly IBusinessModelFactory _businessmodelFactory;
        private readonly ISystemManageModelFactory _systemmanageModelFactory;
        #endregion

        #region Ctor
        public BackendBusinessController(ISystemModuleService systemmoduleService,
           IWorkContext workContext,
           NewsSettings newsSettings,
           BlogSettings blogSettings,
           ILanguageService languageService,
           IFileUploadService fileuploadService,
           IPermissionService permissionService,
           IBusinessModelFactory businessmodelFactory,
           IGenericAttributeService genericattributeService,
           ISystemManageModelFactory systemmanagemodelFactory)
        {
            this._workContext = workContext;
            this._newsSettings = newsSettings;
            this._blogSettings = blogSettings;
            this._languageService = languageService;
            this._gaService = genericattributeService;
            this._fileuploadService = fileuploadService;
            this._permissionService = permissionService;
            this._systemmoduleService = systemmoduleService;
            this._businessmodelFactory = businessmodelFactory;
            this._systemmanageModelFactory = systemmanagemodelFactory;
        }
        #endregion

        #region ColumnManage
        public virtual IActionResult BackendColumnManage()
        {
            string moduleUri = BackendAuthorizeRouteConfig.BackendBusiness_ColumnManage;
            var CurrentSystemModule = _systemmoduleService.GetSystemModuleByUri(moduleUri);
            if (!_permissionService.Authorize(CurrentSystemModule))
                return AccessDeniedView();
            ViewBag.PageTitle = CurrentSystemModule.DisplayName;
            ViewBag.CurrentSystemModuleId = CurrentSystemModule.Id;
            var model = new ColumnItemModel();
            return View(model);
        }
        [AuthorizeButton]
        public virtual IActionResult BackendColumnManageEdit(int moduleid, int buttonid, int columnid)
        {
            ViewBag.PageTitle = "编辑栏目菜单信息";
            var languages = _languageService.GetLanguagesAll();
            var columnModel = _businessmodelFactory.PrepareColumnItemModel(columnid);
            var lang = languages.FirstOrDefault(l => l.Id == columnModel.LanguageId);
            if (lang == null) lang = languages.First();
            columnModel.LanguageId = lang.Id;
            columnModel.LanguageCulture = lang.Culture;
            columnModel.LanguageCode = lang.LanguageCode;

            var AvailableColumnTypes = new List<SelectListItem>()
            {
                new SelectListItem("首页导航", nameof(EntityEnumConfig.ColumnType.HomeIndex), columnModel.ColumnType == EntityEnumConfig.ColumnType.HomeIndex ? true : false),
                //new SelectListItem("新闻/文章导航", nameof(EntityEnumConfig.ColumnType.NewsColumn), columnModel.ColumnType == EntityEnumConfig.ColumnType.NewsColumn ? true : false),
                //new SelectListItem("博客栏导航", nameof(EntityEnumConfig.ColumnType.BlogColumn), columnModel.ColumnType == EntityEnumConfig.ColumnType.BlogColumn ? true : false)
            };
            if (_newsSettings.Enabled) AvailableColumnTypes.Add(new SelectListItem("新闻/文章导航", nameof(EntityEnumConfig.ColumnType.NewsColumn), columnModel.ColumnType == EntityEnumConfig.ColumnType.NewsColumn ? true : false));
            if (_blogSettings.Enabled) AvailableColumnTypes.Add(new SelectListItem("博客栏导航", nameof(EntityEnumConfig.ColumnType.BlogColumn), columnModel.ColumnType == EntityEnumConfig.ColumnType.BlogColumn ? true : false));
            Func<Language, SelectListItem> SelectLanguageModel = (lang) =>
            {
                return new SelectListItem(lang.DisplayName, lang.Id.ToString(), columnModel.LanguageId == lang.Id ? true : false);
            };
            var AvailableLanguages = languages.Select(entity => SelectLanguageModel.Invoke(entity)).ToList();
            var AvailableUrlTarget = new List<SelectListItem>()
            {
                new SelectListItem("页面跳转", nameof(EntityEnumConfig.UrlTarget.Self), true),
                new SelectListItem("新窗口打开", nameof(EntityEnumConfig.UrlTarget.NewWindow), false)
            };
            var AvailablLayoutType = new List<SelectListItem>()
            {
                new SelectListItem("列表展示", nameof(EntityEnumConfig.PageLayoutType.ArticleList), true),
                new SelectListItem("单页详情", nameof(EntityEnumConfig.PageLayoutType.SingleDetailPage), false)
            };
            ViewBag.AvailableColumnTypes = AvailableColumnTypes;
            ViewBag.AvailableLanguages = AvailableLanguages;
            ViewBag.AvailableUrlTarget = AvailableUrlTarget;
            ViewBag.AvailablLayoutType = AvailablLayoutType;
            ViewBag.AvailableListLayout = PageAvailableLayoutTemplate.AvailableListLayout;
            ViewBag.AvailableDetailLayout = PageAvailableLayoutTemplate.AvailableDetailLayout;
            return View(columnModel);
        }
        #endregion

        #region NewsManage
        public virtual IActionResult BackendNewsManage()
        {
            if (!_newsSettings.Enabled)
                return AccessDeniedView();
            string moduleUri = BackendAuthorizeRouteConfig.BackendBusiness_NewsManage;
            var CurrentSystemModule = _systemmoduleService.GetSystemModuleByUri(moduleUri);
            if (!_permissionService.Authorize(CurrentSystemModule))
                return AccessDeniedView();
            var newsItemModel = _businessmodelFactory.PrepareNewsItemModel();
            var searchModel = new NewsItemSearchModel();
            searchModel.SetGridPageSize();
            newsItemModel.CustomProperties.Add("NewsItemSearchModel", searchModel);
            ViewBag.PageTitle = CurrentSystemModule.DisplayName;
            ViewBag.CurrentSystemModuleId = CurrentSystemModule.Id;
            ViewBag.ColumnTreeType = (int)EntityEnumConfig.ColumnType.NewsColumn;
            //Get ModuleAssignedButtons 为文章检索提供按钮操作
            var moduleAssignedBtns = _permissionService.GetSystemModuleAssignedButtons(moduleUri);
            ViewBag.ModuleAssignedBtns = moduleAssignedBtns == null ? null : moduleAssignedBtns.Where(m => m.ButtonType == EntityEnumConfig.SystemModuleButtonType.RecordBtn).ToList();
            return View(newsItemModel);
        }
        [AuthorizeButton]
        public virtual IActionResult BackendNewsManageEdit(int moduleid, int buttonid, int newsid = 0, int columnid = 0, bool copy = false)
        {
            ViewBag.PageTitle = "编辑新闻/文章信息";
            var CurrentUser = _workContext.CurrentAdminUser;
            var newsItemModel = _businessmodelFactory.PrepareNewsItemModel(newsid);
            if (newsItemModel == null) return PageNotFoundView();
            //DavidLee 2020/08/03 增加栏目权限控制
            ViewBag.ButtonId = buttonid;
            if (newsid > 0 && _newsSettings.Enabled && _newsSettings.ColumnAuthorize)
            {//编辑新闻检查用户栏目权限
             //Edit or Copy
                if (!_permissionService.AuthorizeColumnButton(newsItemModel.FKColumnId, buttonid))
                    return AccessDeniedView();
            }
            else if (newsid == 0 && columnid > 0)
            {//DavidLee 2020/08/17 增加点击对应栏目时点击添加文章在文章编辑页面栏目树自动选择对应栏目
                var newAddArticleColumn = _businessmodelFactory.PrepareColumnItemModel(columnid);
                if (newAddArticleColumn != null)
                {
                    newsItemModel.FKColumnId = columnid;
                    if (_newsSettings.Enabled && _newsSettings.ColumnAuthorize)
                        if (!_permissionService.AuthorizeColumnButton(columnid, buttonid))
                            return AccessDeniedView();
                }
            }

            if (string.IsNullOrEmpty(newsItemModel.CoverImageUrl))
                newsItemModel.CoverImageUrl = "0;" + _fileuploadService.GetDefaultFileUrl(FileType.Image);
            if (string.IsNullOrEmpty(newsItemModel.Publisher))
                newsItemModel.Publisher = CurrentUser.UserName;
            //浏览权限查询
            switch (newsItemModel.WhoCanSee)
            {
                case EntityEnumConfig.WhoCanSee.OnlyMe: //自己可见
                    if (string.IsNullOrEmpty(newsItemModel.UserOrRoleId)) throw new NowaException("文章权限设置错误");
                    else if (int.Parse(newsItemModel.UserOrRoleId) != CurrentUser.Id) return AccessDeniedView();
                    break;
                case EntityEnumConfig.WhoCanSee.OnlyAdminRole: //指定用户角色可见
                    if (string.IsNullOrEmpty(newsItemModel.UserOrRoleId)) throw new NowaException("文章权限设置错误");
                    else
                    {
                        var userRoles = CurrentUser.GetAdminRoles();
                        var authRoles = newsItemModel.UserOrRoleId.Split(',').Select(Int32.Parse).ToArray();
                        if (!userRoles.Any(r => authRoles.Contains(r.Id)))
                            return AccessDeniedView();
                    }
                    break;
                case EntityEnumConfig.WhoCanSee.OnlyAdminUser: //仅系统管理员可见
                    if (!_workContext.IsAdmin) return AccessDeniedView();
                    break;
                default:
                    break;
            }

            var languages = _languageService.GetLanguagesAll();
            Func<Language, SelectListItem> SelectLanguageModel = (lang) =>
            {
                return new SelectListItem(lang.DisplayName, lang.Id.ToString(), lang.Culture == "zh-CN" ? true : false); //设置默认语言为中文 
            };
            var AvailableLanguages = languages.Select(entity => SelectLanguageModel.Invoke(entity)).ToList();
            var AvailableViewer = new List<SelectListItem>()
            {
                new SelectListItem("开放浏览", nameof(EntityEnumConfig.WhoCanSee.EveryOne), true),
                new SelectListItem("私密浏览", nameof(EntityEnumConfig.WhoCanSee.OnlyMe), false),
                new SelectListItem("指定用户角色可见", nameof(EntityEnumConfig.WhoCanSee.OnlyAdminRole), false),
                new SelectListItem("系统管理员可见", nameof(EntityEnumConfig.WhoCanSee.OnlyAdminUser), true),

            };
            var AvailablePublishStyle = new List<SelectListItem>()
            {
                new SelectListItem("立即发布", "now", true),
                new SelectListItem("定时发布", "schedule", false)
            };
            ViewBag.AvailableViewer = AvailableViewer;
            ViewBag.AvailablePublishStyle = AvailablePublishStyle;
            ViewBag.AvailableLanguages = AvailableLanguages;
            ViewBag.CurrentUser = CurrentUser;
            ViewBag.ColumnTreeType = (int)EntityEnumConfig.ColumnType.NewsColumn;
            //图片相册,视频列表，文件列表，音频列表查询
            IList<GenericAttribute> newsItemExtraInfo = _gaService.GetAttributesForEntity(newsItemModel.Id, nameof(NewsItem));
            if (newsItemExtraInfo != null)
            {
                #region 抛弃原有写法
                //var tempGeneric = newsItemExtraInfo.FirstOrDefault(ex => ex.Key == nameof(newsItemModel.ImageIds));
                //newsItemModel.ImageIds = tempGeneric?.Value.Split(',').Select(Int32.Parse).ToArray() ?? null;
                //tempGeneric = newsItemExtraInfo.FirstOrDefault(ex => ex.Key == nameof(newsItemModel.ImageUrls));
                //newsItemModel.ImageUrls = tempGeneric?.Value.Split(',').ToArray() ?? null;
                //tempGeneric = newsItemExtraInfo.FirstOrDefault(ex => ex.Key == nameof(newsItemModel.VideoIds));
                //newsItemModel.VideoIds = tempGeneric?.Value.Split(',').Select(Int32.Parse).ToArray() ?? null;
                //tempGeneric = newsItemExtraInfo.FirstOrDefault(ex => ex.Key == nameof(newsItemModel.VideoUrls));
                //newsItemModel.VideoUrls = tempGeneric?.Value.Split(',').ToArray() ?? null;
                //tempGeneric = newsItemExtraInfo.FirstOrDefault(ex => ex.Key == nameof(newsItemModel.AudioIds));
                //newsItemModel.AudioIds = tempGeneric?.Value.Split(',').Select(Int32.Parse).ToArray() ?? null;
                //tempGeneric = newsItemExtraInfo.FirstOrDefault(ex => ex.Key == nameof(newsItemModel.AudioUrls));
                //newsItemModel.AudioUrls = tempGeneric?.Value.Split(',').ToArray() ?? null;
                //tempGeneric = newsItemExtraInfo.FirstOrDefault(ex => ex.Key == nameof(newsItemModel.FileIds));
                //newsItemModel.FileIds = tempGeneric?.Value.Split(',').Select(Int32.Parse).ToArray() ?? null;
                //tempGeneric = newsItemExtraInfo.FirstOrDefault(ex => ex.Key == nameof(newsItemModel.FileUrls));
                //newsItemModel.FileUrls = tempGeneric?.Value.Split(',').ToArray() ?? null;
                #endregion
                IList<FileUpload> fileList = null;
                int[] fileIds = null;
                foreach (var attribute in newsItemExtraInfo)
                {
                    CommonHelper.SetProperty(newsItemModel, attribute.Key, attribute.Value);
                    if (attribute.Key.IndexOf("Ids") > 0)
                    {
                        fileIds = attribute.Value.Split(',').Select(Int32.Parse).ToArray();
                        fileList = _fileuploadService.GetFileUploadList(fileIds);
                        string propName = attribute.Key.Substring(0, attribute.Key.IndexOf("Ids")) + "Urls";
                        CommonHelper.SetProperty(newsItemModel, propName, fileList.Select(f => _fileuploadService.GetFileUrl(f)).ToList());
                        newsItemModel.FileTitles = fileList.Select(f => string.IsNullOrEmpty(f.TitleAttribute) ? f.SeoFilename : f.TitleAttribute).ToList();
                    }

                }
            }
            if (copy) newsItemModel.Id = 0;
            return View(newsItemModel);
        }
        #endregion

        #region ResourceManage
        public virtual IActionResult BackendResourceManage()
        {
            string moduleUri = BackendAuthorizeRouteConfig.BackendBusiness_ResourceManage;
            var CurrentSystemModule = _systemmoduleService.GetSystemModuleByUri(moduleUri);
            if (!_permissionService.Authorize(CurrentSystemModule))
                return AccessDeniedView();
            var fileItem = new FileItemModel();
            var searchModel = new FileItemSearchModel();
            searchModel.SetGridPageSize(12, "8,12,16");
            fileItem.CustomProperties.Add("FileItemSearchModel", searchModel);

            //Get ModuleAssignedButtons 
            var moduleAssignedBtns = _permissionService.GetSystemModuleAssignedButtons(moduleUri);
            ViewBag.ModuleAssignedBtns = moduleAssignedBtns == null ? null : moduleAssignedBtns.Where(m => m.ButtonType == EntityEnumConfig.SystemModuleButtonType.RecordBtn).ToList();
            ViewBag.PageTitle = CurrentSystemModule.DisplayName;
            ViewBag.CurrentSystemModuleId = CurrentSystemModule.Id;
            return View(fileItem);
        }

        [AuthorizeButton]
        public virtual IActionResult BackendResourceManageEdit(int moduleid, int buttonid, int resourceid)
        {
            ViewBag.PageTitle = "编辑";
            var fileItemModel = _businessmodelFactory.PrepareFileItemModel(resourceid);
            if (fileItemModel == null) return PageNotFoundView();
            
            var AvailableFileType = new List<SelectListItem>()
            {
                new SelectListItem(UploadUseCategory.NewsCarouselImage, nameof(UploadUseCategory.NewsCarouselImage), true),
                new SelectListItem(UploadUseCategory.NewsVideos, nameof(UploadUseCategory.NewsVideos), false),
                new SelectListItem(UploadUseCategory.NewsAudios, nameof(UploadUseCategory.NewsAudios), false),
                new SelectListItem(UploadUseCategory.NewsTextFiles, nameof(UploadUseCategory.NewsTextFiles), false),
                new SelectListItem(UploadUseCategory.BlogVideos, nameof(UploadUseCategory.BlogVideos), false),
                new SelectListItem(UploadUseCategory.BlogAudios, nameof(UploadUseCategory.BlogAudios), false),
                new SelectListItem(UploadUseCategory.BlogTextFiles, nameof(UploadUseCategory.BlogTextFiles), false),

            };
            var AvailableStoreType = new List<SelectListItem>()
            {
                new SelectListItem("本地", nameof(EntityEnumConfig.FileStoreType.LocalStorage), true),
                new SelectListItem("云存储", nameof(EntityEnumConfig.FileStoreType.QiniuCloud), false)
            };
            ViewBag.AvailableFileType = AvailableFileType;
            ViewBag.AvailableStoreType = AvailableStoreType;
            
            return View(fileItemModel);
        }
        #endregion

        #region AdvertiseManage
        public virtual IActionResult BackendAdvertiseManage()
        {
            string moduleUri = BackendAuthorizeRouteConfig.BackendBusiness_AdvertiseManage;
            var CurrentSystemModule = _systemmoduleService.GetSystemModuleByUri(moduleUri);
            if (!_permissionService.Authorize(CurrentSystemModule))
                return AccessDeniedView();
            ViewBag.PageTitle = CurrentSystemModule.DisplayName;
            ViewBag.CurrentSystemModuleId = CurrentSystemModule.Id;
            var model = new AdvertiseBannerModel();
            var searchModel = new AdvertiseBannerSearchModel();
            searchModel.SetGridPageSize();
            model.CustomProperties.Add("AdvertiseBannerSearchModel", searchModel);
            return View(model);
        }

        [AuthorizeButton]
        public virtual IActionResult BackendAdvertiseManageEdit(int moduleid, int buttonid, int advid)
        {
            ViewBag.PageTitle = "编辑广告栏信息";
            var advItemModel = _businessmodelFactory.PrepareAdvertiseBannerModel(advid);
            if (advItemModel == null) return PageNotFoundView();
           
            var AvailableDisplayType = new List<SelectListItem>()
            {
                new SelectListItem("PC端展示", nameof(EntityEnumConfig.AdertiseDisplay.PC), true),
                new SelectListItem("手机端展示", nameof(EntityEnumConfig.AdertiseDisplay.Mobile), false)
            };
            var AvailableAdvType = new List<SelectListItem>()
            {
                new SelectListItem("轮播图列表", nameof(EntityEnumConfig.AdertiseType.CarouselImages), true),
                new SelectListItem("友情链接(文字)", nameof(EntityEnumConfig.AdertiseType.TextLinks), false),
                new SelectListItem("友情链接(图片)", nameof(EntityEnumConfig.AdertiseType.ImageLinks), false),
                new SelectListItem("固定位置单图", nameof(EntityEnumConfig.AdertiseType.StaticImage), false),
                new SelectListItem("图片栅格矩阵", nameof(EntityEnumConfig.AdertiseType.GridLayout), false)
            };
            ViewBag.AvailableDisplayType = AvailableDisplayType;
            ViewBag.AvailableAdvType = AvailableAdvType;
            return View(advItemModel);
        }
        #endregion

        #region CommentManage
        public virtual IActionResult BackendCommentManage()
        {
            string moduleUri = BackendAuthorizeRouteConfig.BackendBusiness_CommentManage;
            var CurrentSystemModule = _systemmoduleService.GetSystemModuleByUri(moduleUri);
            if (!_permissionService.Authorize(CurrentSystemModule))
                return AccessDeniedView();
            ViewBag.PageTitle = CurrentSystemModule.DisplayName;
            ViewBag.CurrentSystemModuleId = CurrentSystemModule.Id;
            //Get ModuleAssignedButtons 
            var moduleAssignedBtns = _permissionService.GetSystemModuleAssignedButtons(moduleUri);
            ViewBag.ModuleAssignedBtns = moduleAssignedBtns == null ? null : moduleAssignedBtns.Where(m => m.ButtonType == EntityEnumConfig.SystemModuleButtonType.RecordBtn).ToList();
            var model = new CommentItemModel();
            var searchModel = new CommentSearchModel();
            searchModel.SetGridPageSize();
            model.CustomProperties.Add("CommentSearchModel", searchModel);

            var FilterSearch = new List<SelectListItem>()
            {
                new SelectListItem("未回复", nameof(EntityEnumConfig.YesorNo.No), true),
                new SelectListItem("已回复", nameof(EntityEnumConfig.YesorNo.YES), false)
            };
            ViewBag.FilterSearch = FilterSearch;

            return View(model);
        }
        #endregion

        #region BlogManage
        public virtual IActionResult BackendBlogManage()
        {
            if (!_blogSettings.Enabled)
                return AccessDeniedView();
            string moduleUri = BackendAuthorizeRouteConfig.BackendBusiness_BlogManage;
            var CurrentSystemModule = _systemmoduleService.GetSystemModuleByUri(moduleUri);
            if (!_permissionService.Authorize(CurrentSystemModule))
                return AccessDeniedView();
            var blogItemModel = _businessmodelFactory.PrepareBlogItemModel();
            var searchModel = new BlogItemSearchModel();
            searchModel.SetGridPageSize();
            blogItemModel.CustomProperties.Add("BlogItemSearchModel", searchModel);
            ViewBag.PageTitle = CurrentSystemModule.DisplayName;
            ViewBag.CurrentSystemModuleId = CurrentSystemModule.Id;
            ViewBag.ColumnTreeType = (int)EntityEnumConfig.ColumnType.BlogColumn;
            //Get ModuleAssignedButtons 为文章检索提供按钮操作
            var moduleAssignedBtns = _permissionService.GetSystemModuleAssignedButtons(moduleUri);
            ViewBag.ModuleAssignedBtns = moduleAssignedBtns == null ? null : moduleAssignedBtns.Where(m => m.ButtonType == EntityEnumConfig.SystemModuleButtonType.RecordBtn).ToList();
            return View(blogItemModel);
        }

        [AuthorizeButton]
        public virtual IActionResult BackendBlogManageEdit(int moduleid, int buttonid, int blogid, bool copy = false)
        {
            ViewBag.PageTitle = "编辑博客文章信息";
            var CurrentUser = _workContext.CurrentAdminUser;
            var blogItemModel = _businessmodelFactory.PrepareBlogItemModel(blogid);
            if (blogItemModel == null) return PageNotFoundView();
            if (string.IsNullOrEmpty(blogItemModel.CoverImageUrl))
                blogItemModel.CoverImageUrl = "0;" + _fileuploadService.GetDefaultFileUrl(FileType.Image);
            if (string.IsNullOrEmpty(blogItemModel.Publisher))
                blogItemModel.Publisher = CurrentUser.UserName;
            //浏览权限查询
            switch (blogItemModel.WhoCanSee)
            {
                case EntityEnumConfig.WhoCanSee.OnlyMe: //自己可见
                    if (string.IsNullOrEmpty(blogItemModel.UserOrRoleId)) throw new NowaException("文章权限设置错误");
                    else if (int.Parse(blogItemModel.UserOrRoleId) != CurrentUser.Id) return AccessDeniedView();
                    break;
                case EntityEnumConfig.WhoCanSee.OnlyAdminRole: //指定用户角色可见
                    if (string.IsNullOrEmpty(blogItemModel.UserOrRoleId)) throw new NowaException("文章权限设置错误");
                    else
                    {
                        var userRoles = CurrentUser.GetAdminRoles();
                        var authRoles = blogItemModel.UserOrRoleId.Split(',').Select(Int32.Parse).ToArray();
                        if (!userRoles.Any(r => authRoles.Contains(r.Id)))
                            return AccessDeniedView();
                    }
                    break;
                case EntityEnumConfig.WhoCanSee.OnlyAdminUser: //仅系统管理员可见
                    if (!_workContext.IsAdmin) return AccessDeniedView();
                    break;
                default:
                    break;
            }

            var languages = _languageService.GetLanguagesAll();
            Func<Language, SelectListItem> SelectLanguageModel = (lang) =>
            {
                return new SelectListItem(lang.DisplayName, lang.Id.ToString(), lang.Culture == "zh-CN" ? true : false); //设置默认语言为中文 
            };
            var AvailableLanguages = languages.Select(entity => SelectLanguageModel.Invoke(entity)).ToList();
            var AvailableViewer = new List<SelectListItem>()
            {
                new SelectListItem("开放浏览", nameof(EntityEnumConfig.WhoCanSee.EveryOne), true),
                new SelectListItem("私密浏览", nameof(EntityEnumConfig.WhoCanSee.OnlyMe), false),
                new SelectListItem("指定用户角色可见", nameof(EntityEnumConfig.WhoCanSee.OnlyAdminRole), false),
                new SelectListItem("系统管理员可见", nameof(EntityEnumConfig.WhoCanSee.OnlyAdminUser), true),

            };
            var AvailablePublishStyle = new List<SelectListItem>()
            {
                new SelectListItem("立即发布", "now", true),
                new SelectListItem("定时发布", "schedule", false)
            };
            ViewBag.AvailableViewer = AvailableViewer;
            ViewBag.AvailablePublishStyle = AvailablePublishStyle;
            ViewBag.AvailableLanguages = AvailableLanguages;
            ViewBag.CurrentUser = CurrentUser;
            ViewBag.ColumnTreeType = (int)EntityEnumConfig.ColumnType.BlogColumn;
            //图片相册,视频列表，文件列表，音频列表查询
            IList<GenericAttribute> blogItemExtraInfo = _gaService.GetAttributesForEntity(blogItemModel.Id, nameof(BlogItem));
            if (blogItemExtraInfo != null)
            {
                IList<FileUpload> fileList = null;
                int[] fileIds = null;
                foreach (var attribute in blogItemExtraInfo)
                {
                    CommonHelper.SetProperty(blogItemModel, attribute.Key, attribute.Value);
                    if (attribute.Key.IndexOf("Ids") > 0)
                    {
                        fileIds = attribute.Value.Split(',').Select(Int32.Parse).ToArray();
                        fileList = _fileuploadService.GetFileUploadList(fileIds);
                        string propName = attribute.Key.Substring(0, attribute.Key.IndexOf("Ids")) + "Urls";
                        CommonHelper.SetProperty(blogItemModel, propName, fileList.Select(f => _fileuploadService.GetFileUrl(f)).ToList());
                    }

                }
            }
            if (copy) blogItemModel.Id = 0;
            return View(blogItemModel);
        }
        #endregion
    }
}
